package br.com.rocks.rs232;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.OnHierarchyChangeListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class ListaDeDispositivosActivity extends Activity {

	protected static final int RESULT_DISCONNECTING_DEVICE = 13;

	private BroadcastReceiver broadcastReceiver;
	private ArrayAdapter<String> bluetoothAdapterPairedDevicesArrayAdapter;
	private ArrayAdapter<String> bluetoothAdapterNewDevicesArrayAdapter;
	private BluetoothDevice bluetoothDevice;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.layout_lista_de_dispositivos);
		setResult(RESULT_CANCELED);

		bluetoothDevice = (BluetoothDevice) getIntent().getExtras().get(BluetoothDevice.EXTRA_DEVICE);

		prepararBroadcastReceiver();

		criarListasDeAdaptadores();

		prepararListaDeAdaptadoresPareados();

		prepararBotaoProcurar();
	}

	private void prepararBroadcastReceiver() {
		broadcastReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				String action = intent.getAction();
				if (BluetoothDevice.ACTION_FOUND.equals(action)) {
					BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
					if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
						bluetoothAdapterNewDevicesArrayAdapter.add(device.getName() + getString(R.string.new_line) + device.getAddress());
					}
				} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
					configBtnProcurar();
				}
			}
		};

		registerReceiver(broadcastReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
		registerReceiver(broadcastReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));
	}

	private void criarListasDeAdaptadores() {
		bluetoothAdapterPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.layout_device_name);
		bluetoothAdapterNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.layout_device_name);

		ListView lstDispositivosPareados = (ListView) findViewById(R.id.lstDispositivosPareados);
		lstDispositivosPareados.setAdapter(bluetoothAdapterPairedDevicesArrayAdapter);
		lstDispositivosPareados.setOnHierarchyChangeListener(new MudaCorDoDispositivoConectado());

		ListView lstDispositivosNovos = (ListView) findViewById(R.id.lstDispositivosNovos);
		lstDispositivosNovos.setAdapter(bluetoothAdapterNewDevicesArrayAdapter);
		lstDispositivosNovos.setOnHierarchyChangeListener(new MudaCorDoDispositivoConectado());
	}

	private class MudaCorDoDispositivoConectado implements OnHierarchyChangeListener {
		@Override
		public void onChildViewRemoved(View parent, View child) {
		}

		@Override
		public void onChildViewAdded(View parent, View child) {
			TextView textView = (TextView) child;
			textView.setOnClickListener(deviceOnItemClickListener());
			textView.setEnabled(bluetoothDevice == null);
			String text = String.valueOf(textView.getText());
			if (bluetoothDevice != null && text.contains(bluetoothDevice.getName()) && text.contains(bluetoothDevice.getAddress())) {
				textView.setBackgroundResource(R.color.background);
				textView.setEnabled(bluetoothDevice != null);
			}
		}
	}

	private OnClickListener deviceOnItemClickListener() {
		return new OnClickListener() {
			@Override
			public void onClick(View v) {
				String item = ((TextView) v).getText().toString();
				boolean naoValido = getString(R.string.nao_existe_dispositivo_pareado).equals(item);
				naoValido = naoValido || getString(R.string.nenhum_dispositivo_encontrado).equals(item);
				naoValido = naoValido || getString(R.string.bluetooth_desligado).equals(item);

				if (!naoValido) {
					BluetoothAdapter.getDefaultAdapter().cancelDiscovery();

					String address = item.substring(item.length() - 17);
					BluetoothDevice bluetoothDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);

					Intent intent = new Intent();
					intent.putExtra(BluetoothDevice.EXTRA_DEVICE, bluetoothDevice);

					int result = RESULT_OK;
					if (bluetoothDevice.equals(ListaDeDispositivosActivity.this.bluetoothDevice)) {
						result = RESULT_DISCONNECTING_DEVICE;
					}
					setResult(result, intent);

					finish();
				}
			}
		};
	}

	private void prepararListaDeAdaptadoresPareados() {
		if (!BluetoothAdapter.getDefaultAdapter().isEnabled()) {
			bluetoothAdapterPairedDevicesArrayAdapter.add(getString(R.string.bluetooth_desligado));
			return;
		}

		if (!BluetoothAdapter.getDefaultAdapter().getBondedDevices().isEmpty()) {
			findViewById(R.id.tituloDispositivosPareados).setVisibility(View.VISIBLE);
			for (BluetoothDevice device : BluetoothAdapter.getDefaultAdapter().getBondedDevices()) {
				bluetoothAdapterPairedDevicesArrayAdapter.add(device.getName() + getString(R.string.new_line) + device.getAddress());
			}
		} else {
			bluetoothAdapterPairedDevicesArrayAdapter.add(getString(R.string.nao_existe_dispositivo_pareado));
		}
	}

	private void prepararBotaoProcurar() {
		Button btnProcurar = (Button) findViewById(R.id.btnProcurar);

		if (!BluetoothAdapter.getDefaultAdapter().isEnabled()) {
			btnProcurar.setVisibility(View.INVISIBLE);
			return;
		}

		btnProcurar.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				if (!BluetoothAdapter.getDefaultAdapter().isDiscovering()) {
					configBtnParar();
					BluetoothAdapter.getDefaultAdapter().startDiscovery();
				} else {
					BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
					configBtnProcurar();
				}
			}
		});
	}

	private void configBtnProcurar() {
		setProgressBarIndeterminateVisibility(false);
		setTitle(R.string.selecione_dispositivo_para_conectar);
		((Button) findViewById(R.id.btnProcurar)).setText(R.string.btn_procurar);
		if (bluetoothAdapterNewDevicesArrayAdapter.isEmpty()) {
			bluetoothAdapterNewDevicesArrayAdapter.add(getString(R.string.nenhum_dispositivo_encontrado));
		}
	}

	private void configBtnParar() {
		findViewById(R.id.tituloNovosDispositivos).setVisibility(View.VISIBLE);
		bluetoothAdapterNewDevicesArrayAdapter.clear();
		setProgressBarIndeterminateVisibility(true);
		setTitle(R.string.procurando_dispositivos);
		((Button) findViewById(R.id.btnProcurar)).setText(R.string.btn_parar);
	}

	@Override
	protected void onDestroy() {
		BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
		unregisterReceiver(broadcastReceiver);

		super.onDestroy();
	}
}
